package server;

import container.Context;
import container.Host;
import container.Mapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import servlet.ContextLoader;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    private Mapper mapper = new Mapper();

    /**
     * 定义socket监听的端口号
     */
    private int port;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 解析server.xml
       loadServer();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );


        ServerSocket serverSocket = new ServerSocket(port);

        /*
            多线程改造（使用线程池）
         */
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, mapper);
            threadPoolExecutor.execute(requestProcessor);
        }
    }


    /**
     * 加载解析server.xml，初始化容器
    */
    private void loadServer() throws DocumentException {
        // 加载解析server.xml配置文件
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        Document document = saxReader.read(resourceAsStream);
        Element rootElement = document.getRootElement();


        // 设置端口号
        Element connectorElement = (Element) rootElement.selectSingleNode("//Connector");
        int port = Integer.parseInt(connectorElement.attribute("port").getValue());
        setPort(port);

        // 部署目录的绝对路径
        Element hostElement = (Element) rootElement.selectSingleNode("//Host");
        String hostName = hostElement.attribute("name").getValue();
        String appBase = hostElement.attribute("appBase").getValue();

        Host host = new Host(hostName);


        // 设置web应用的绝对路径和uri映射
        List<Element> selectContexts = hostElement.selectNodes("Context");
        if (selectContexts != null) {
            for (Element contextElement : selectContexts) {

                String name = contextElement.attribute("docBase").getValue();
                String uriPath = contextElement.attribute("path").getValue();

                Context context = new Context(name, appBase + uriPath);
                ContextLoader contextLoader = new ContextLoader(context);
                contextLoader.load();
                host.addContext(context);
            }
        }else {
            Context context = new Context("/", appBase);
            ContextLoader contextLoader = new ContextLoader(context);
            contextLoader.load();

            host.addContext(context);
        }
        mapper.addHost(host);
    }

    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
